import { UpdateWriteOpResult } from 'mongoose';
import { formatDateByNow } from '~/utils/util.date';
import { AdminUserModel } from '~/server/models/admin_user.model';
import { checkAdminUserPermission } from '~/server/utils/util.permissionVerification';

/**
 * @api {patch} /admin/user/resetPassword 重置用户密码
 * @apiName 重置用户密码
 * @apiGroup 后台管理员用户
 * @apiDescription 重置用户密码，仅用于超级管理员（admin用户）重置其他用户的密码，重置多个需使用英文逗号分隔 ID，如果用户密码本身是重置后的密码，则不受影响
 *
 * @apiPermission admin
 *
 * @apiSampleRequest /admin/user/resetPassword
 *
 * @apiHeader {String} Authorization 用户 Token
 *
 * @apiQuery {String} id 用户 ID
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '成功重置 1 个用户的密码',
 * }
 */
export default defineEventHandler(async (event) => {
	const checkPermission = checkAdminUserPermission(event, 'admin');
	if (!checkPermission) {
		return {
			code: 0,
			message: '无权访问',
		};
	}

	const { id } = getQuery(event);

	if (!id || typeof id !== 'string') {
		return {
			code: 0,
			message: '参数错误',
		};
	}

	// 处理用户 ID，支持批量重置
	const ids: string[] = id.split(',');

	try {
		const updateResult: UpdateWriteOpResult = await AdminUserModel.updateMany(
			{ _id: { $in: ids } },
			{ password: sha256(md5('Abc123987')), updatedAt: formatDateByNow() }
		);

		return {
			code: 1,
			message: `成功重置 ${updateResult.modifiedCount} 个用户的密码`,
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
